package com.qianfeng.xiaxk.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;


import com.qianfeng.xiaxk.R;
import com.qianfeng.xiaxk.activity.LoginActivity;
import com.qianfeng.xiaxk.inter.OnFragmentChangeListener;

import java.util.List;

/**
 * Created by Administrator on 2015/7/22.
 */
public class FragmentTagUtils implements RadioGroup.OnCheckedChangeListener {
    RadioGroup rg;
    FragmentManager manager;
    List<Fragment> fragmentList;
    int containerId;
    OnFragmentChangeListener listener;
    Activity activity;
    public int currentCheckId;///当前选中的radioButton的id
    public int expectedCheckedId;////期望选中的id

    public void setListener(OnFragmentChangeListener listener) {
        this.listener = listener;
    }

    public FragmentTagUtils(Activity activity,RadioGroup rg, int contianerId, FragmentManager manager, List<Fragment> fragmentList) {
        this.activity = activity;
        this.rg = rg;
        this.manager = manager;
        this.fragmentList = fragmentList;
        this.containerId = contianerId;
        rg.setOnCheckedChangeListener(this);//这两句代码不要搞错位置了
        ((RadioButton) (rg.getChildAt(0))).setChecked(true);
        currentCheckId = ((RadioButton) (rg.getChildAt(0))).getId();
        manager.beginTransaction().show(fragmentList.get(0)).commit();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        expectedCheckedId = checkedId;
        if(checkedId== R.id.main_footer_chat_rb && !LoginUtils.isLogin(activity)){
            ((RadioButton)  group.findViewById(currentCheckId)).setChecked(true);
            activity.startActivityForResult(new Intent(activity, LoginActivity.class),1);
        }else {
            for (int i = 0; i < rg.getChildCount(); i++) {
                Fragment fragment = fragmentList.get(i);
                if (rg.getChildAt(i).getId() == checkedId) {
                    if (!fragment.isAdded()) {
                        manager.beginTransaction().add(containerId, fragment).commit();
                    }
                    currentCheckId = checkedId;
                    manager.beginTransaction().show(fragment).commit();
                } else {
                    manager.beginTransaction().hide(fragment).commit();
                }
            }
        }
        if (listener != null) {
            listener.onFragmentChange(group, checkedId);
        }
    }
}
